/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-03-31 11:58:58
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-23 09:39:58
 */
import { onMounted } from 'vue'
import apiMod from '@/apiMod/index'
import { useCommonStore } from '@/stores/common'
import { getStore } from '@/utils/store'
import bus from '@/utils/eventbus'
export default defineComponent({
	name: 'AplidRemote',
	props: {
		modelValue: {
			type: [Array, String, Number],
		},
		modelName: {
			type: String,
		},
		tipLabel: {
			type: String,
			required: false
		},
		code: {
			type: String,
		},
		api: {
			type: String,
			default: '',
		},
		filterLabel: {
			type: String,
			default: 'label',
		},
		filterKey: {
			type: String,
			default: 'value',
		},
		dataType: {
			type: String,
			default: 'string',
		},
		prop: {
			type: String,
			default: 'string',
		},
		allowCreate: {
			type: Boolean,
			default: false,
		},
		multiple: {
			type: Boolean,
			default: false,
		},
		remote: {
			type: Boolean,
			default: true,
		},
		filterable: {
			type: Boolean,
			default: true,
		},
		paramsObj: {
			type: Object,
			default: () => ({}),
		},
		dicData: {
			type: Array,
			default: () => [],
		},
	},
	emits: ['update:modelValue', 'update:modelName', 'change'],
	setup(props, { attrs, emit }) {
		const selectValue: any = ref('')
		let elOption: any = ref(props.dicData)
		let loading = ref(false)
		const remoteQuery = ref({}) as any

		const dictCode = ref(props.code)
		let pageReac = ref({
			total: 0,
			size: 15,
			current: 1,
		})
		// 动态管理查询字段
		bus.on(`remote-search-params-${props.prop}`, (item?: any) => {
			if (props.prop) {
				if (typeof item == 'string') {
					dictCode.value = item
				} else {
					remoteQuery.value = item
				}
				if (props.api) remoteMethod('init')
			}
		})

		const initChange = (valueKey: any, sourceType?: string) => {
			const keys = Array.isArray(valueKey) ? valueKey : [valueKey]
			const checked = elOption.value.filter((item: any) => keys.includes(item.value))
			const getLabel = (value) => {
				if (!value) return ''
				return checked.map((item) => item.label)
			}

			let dataLabel
			if (attrs.propName) {
				const data = getLabel(valueKey)
				dataLabel = data && data.toString()
			}
			emit('update:modelName', dataLabel || props.modelName)
			bus.emit('remote-change', {
				api: props.api,
				sourceType,
				value: valueKey,
				label: dataLabel,
			})
		}
		const onChange = (valueKey: any, sourceType?: string) => {
			const keys = Array.isArray(valueKey) ? valueKey : [valueKey]
			const checked = elOption.value.filter((item: any) => keys.includes(item.value))
			let kvalue = checked.map((item) => item.value)
			if (kvalue.length == 0) {
				kvalue = valueKey
			}
			const getLabel = (value) => {
				if (!value) return ''
				return checked.map((item) => item.label)
			}
			let dataLabel
			if (attrs.propName) {
				const data = getLabel(valueKey)
				dataLabel = data && data.toString()
				emit('update:modelName', dataLabel || props.modelName)
			}
			let item = elOption.value.find((item: any) => item.value === valueKey) as any
			emit('change', { ...item, sourceType })
			if (props.multiple) {
				emit('update:modelValue', props.dataType == 'string' && Array.isArray(kvalue) ? kvalue.join(',') : kvalue)
			} else {
				emit('update:modelValue', Array.isArray(kvalue) ? kvalue.join(',') : kvalue)
			}
			bus.emit('remote-change', {
				api: props.api,
				sourceType,
				value: valueKey,
				label: dataLabel,
			})
		}
		const remoteMethod = async (query: string) => {
			const { dictList } = useCommonStore()
			let params: any = {}
			if (query) {
				if (query != 'init') params[props.filterLabel] = query
				let dataList = []
				if (props.code || dictCode.value) {
					params.code = dictCode.value || props.code
					dataList = dictList[dictCode.value || props.code] || []
				} else {
					params.pageParaPO = {
						current: pageReac.value.current,
						size: pageReac.value.size,
					}
				}
				if (props.paramsObj.pageParaPO) {
					pageReac.value.size = props.paramsObj?.pageParaPO?.size
				}

				loading.value = true

				if (dataList.length == 0) {
					const queryObj = props.code
						? [dictCode.value || props.code]
						: {
								...params,
								...props.paramsObj,
								...remoteQuery.value,
						  }
					if (apiMod[props.api]) {
						const { data } = await apiMod[props.api](queryObj)
						if (data.total) {
							pageReac.value.total = data.total
							pageReac.value.current = data.current
						} else {
							pageReac.value.total = 0
						}

						dataList = Array.isArray(data) ? data : data.records
						if (!dataList) {
							dataList = data[dictCode.value || props.code] || []
						}
					}
				}
				if (dataList && dataList.length > 0) {
					elOption.value = dataList.map((item) => {
						let value = item[props.filterKey]
						return {
							...item,
							label: item[props.filterLabel],
							value: `${value}`,
						}
					})
				} else {
					elOption.value = []
				}
				if (props.modelName && props.modelValue) {
					const tempValue: any = props.modelValue
					const tempName: any = props.modelName
					const _v: any = tempValue?.split(',') || []
					const _n: any = tempName?.split(',') || []
					const _data = _v
						.map((item, index) => {
							const _temp = elOption.value.findIndex((v) => v.value == item)
							if (_temp == -1) {
								return {
									label: _n[index],
									value: `${_v[index]}`,
								}
							}
						})
						.filter(Boolean)

					elOption.value = [...elOption.value, ..._data]
				}
				loading.value = false
			} else {
				elOption.value = []
			}
			const userInfo = getStore('userInfo') || {}
			if (props.api == 'view_dpServiceOrgBase_page' && userInfo.organizationId && userInfo.organizationId != 1) {
				setTimeout(() => {
					onChange(userInfo.organizationId)
				}, 500)
			}
		}
		const onFocused = () => {
			// if (elOption.value.length == 0 && props.api) {
			// 	setTimeout(() => {
			// 		remoteMethod('init')
			// 	}, 500)
			// }
		}
		const handleClear = () =>{
			emit('update:modelName', undefined)
			emit('update:modelValue', undefined)
		}

		watch(
			() => props.modelValue,
			(value) => {
				let tempValue: any = value
				if (value || value == 0) {
					if (value && typeof value == 'string') {
						tempValue = props.multiple ? value.split(',') : value
					} else if (value == 0) {
						tempValue = '0'
					} else {
						tempValue = props.multiple ? value || [] : `${value}`
					}
				} else {
					tempValue = ''
				}
				selectValue.value = tempValue
				if (Array.isArray(tempValue)) {
					selectValue.value = tempValue.map((v) => {
						return `${v}`
					})
				}

				if (selectValue.value && props.modelValue) {
					setTimeout(() => {
						initChange(selectValue.value, 'init')
					}, 200)
				}
			},
			{
				immediate: true,
			}
		)

		watch(
			() => props.paramsObj,
			(val) => {
				if (props.api) remoteMethod('init')
			}
		)

		const onCurrentChange = (val: number) => {
			pageReac.value.current = val
			remoteMethod('init')
		}

		onMounted(() => {
			if (props.api) remoteMethod('init')
		})

		const slotsObj: any = {}
		slotsObj.default = ({ item }) => (
			<div class="f-between">
				<p style="margin-right: 8px">{item.label}</p>
				<p style="margin-right: 8px">{item[props.tipLabel]}</p>
			</div>
		)

		slotsObj.footer = () => (
			<div>
				<el-pagination
					hide-on-single-page
					v-model:current-page={pageReac.value.current}
					v-model:page-size={pageReac.value.size}
					onCurrentChange={(val) => onCurrentChange(val)}
					small
					layout="prev, pager, next"
					total={pageReac.value.total}
				/>
			</div>
		)
		return () => {
			return (
				<el-select-v2
					onChange={onChange}
					onFocus={onFocused}
					clearable
					onClear={handleClear}
					remote={props.remote}
					name="select"
					allowCreate={props.allowCreate}
					filterable={props.code ? false : props.filterable}
					validate-event={false}
					multiple={props.multiple}
					reserve-keyword={false}
					loading={loading.value}
					remote-method={remoteMethod}
					options={elOption.value}
					vModel={selectValue.value}
				>
					{slotsObj}
				</el-select-v2>
			)
		}
	},
})
